package com.xquant.marketdata.curvestrip.service.impl;

import com.alibaba.fastjson2.JSON;
import com.github.pagehelper.PageInfo;
import com.xquant.marketdata.curvestrip.mapper.DictMapper;
import com.xquant.marketdata.curvestrip.mapper.IrCurvePaperMapper;
import com.xquant.marketdata.curvestrip.service.IrCurvePaperService;
import com.xquant.marketdata.utils.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;


@Service(IrCurvePaperService.BEAN_NAME)
public class IrCurvePaperServiceImpl implements IrCurvePaperService {

    @Autowired
    private IrCurvePaperMapper paperMapper;
    @Autowired
    private DictMapper dictMapper;

    @Override
    public PageInfo<Map> queryIrCurveFormDataByPage(Map<String, Object> param) {
        HashMap<String, Object> dictType = new HashMap<>();
        dictType.put("DICT_TYPE", "irCurve");
        List<Map> dictCurves = dictMapper.queryIrDictByKey(dictType);
        String ircCodes = "";
        for (Map e : dictCurves) {
            String dictKey = (String) e.get("DICT_KEY");
            ircCodes += "'" + dictKey + "',";
        }
        param.put("ircCodes", ircCodes.substring(0, ircCodes.length() - 1));

        param.put("ruleDate", param.get("ruleDate") == null ? DateUtils.getCurrentDate() : param.get("ruleDate"));
        List<Map> list = paperMapper.queryIrCurvePaperByPage(param);
        List<Map> record = rowToColumn(list);


        //格式化数据
        DecimalFormat df = new DecimalFormat("0.0000");//返回数据模板，小数点后两位
        record = record.stream().map(el -> {
            Set<String> set = el.keySet();
            for (String k : set) {
                if (k.equals("IRC_CODE") || k.equals("ELEM")) {
                    continue;
                } else {
                    el.put(k, df.format(new BigDecimal(el.get(k).toString())));
                }
            }
            return el;
        }).collect(Collectors.toList());

        return new PageInfo<>(list);
    }

    private List<Map> rowToColumn(List<Map> list) {
        List<Map> elem1 = list.stream().map(el -> {
                    String elem = (String) el.get("ELEM");

                    if (StringUtils.isEmpty(elem)){
                        return el;//空值直接返回，减少操作耗时，避免空指针
                    }
                    String[] split = elem.split(",");//字符串操作得到每个属性值
                    Arrays.stream(split).map(kv -> {
                        String[] es = kv.split(":");//字符串操作得到kv
                        //去掉rates表中的rate数据所包含的  ''
                        es[0] = es[0].replace("'", "").trim();
                        el.put(es[0].contains(".") ? es[0].replace('.', '-') : es[0],
                                es[1]);//dataIndex不能包含小数点
                        return kv;
                    }).collect(Collectors.toList());
                    return el;
                }
        ).collect(Collectors.toList());


        return elem1;
    }

    @Override
    public PageInfo<Map> getIrCurveFormChangeData(Map<String, Object> param) {
        DecimalFormat df = new DecimalFormat("0.00");//返回数据模板，小数点后两位

        HashMap<String, Object> dictType = new HashMap<>();
        dictType.put("DICT_TYPE", "irCurve");
        List<Map> dictCurves = dictMapper.queryIrDictByKey(dictType);//查字典中曲线

        String ircCodes = "";
        for (Map e : dictCurves) {
            String dictKey = (String) e.get("DICT_KEY");
            ircCodes += "'" + dictKey + "',";//拼接查询条件的曲线代码串
        }
        param.put("ircCodes", ircCodes.substring(0, ircCodes.length() - 1));

        //查询所需日期默认当天
        param.put("ruleDate", param.get("ruleDate") == null ? DateUtils.getCurrentDate() : param.get("ruleDate"));
        //当前日数据，采用当前日减去前一日
        List<Map> currentData = rowToColumn(paperMapper.queryIrCurvePaperByPage(param));

        String ruleDate = (String) param.get("ruleDate");
        //昨天数据
        String yestday = DateUtils.addDate(ruleDate, -1);
        param.put("ruleDate", yestday);
        List<Map> yestdayData = rowToColumn(paperMapper.queryIrCurvePaperByPage(param));

        //计算，当前日减去前一天数据
        List<Map> collect = currentData.stream().map(elm -> {
            Set<String> set = elm.keySet();
            String ircCode = (String) elm.get("IRC_CODE");
            for (String k : set) {
                if (k.equals("IRC_CODE") || k.equals("ELEM")) { //计算不包含此两条key的值
                    continue;
                } else {
                    BigDecimal v = new BigDecimal(String.valueOf(elm.get(k)));

                    //找到匹配的irc_code的记录
                    List<Map> findMatchValue = yestdayData.stream().map(e -> {
                        String yCode = (String) e.get("IRC_CODE");
                        if (yCode.equals(ircCode)) {//找到曲线代码相等的记录返回，其余返回空过滤掉空值
                            return e;
                        } else {
                            return null;
                        }
                    }).filter(Objects::nonNull).collect(Collectors.toList());

                    //排除掉曲线的记录为空与此key对应的值为空的情况
                    String vBaseK = findMatchValue.size() == 0 ? "0.0000000" : String.valueOf(findMatchValue.get(0).get(k) == null ? "0.0000" : findMatchValue.get(0).get(k));

                    BigDecimal newV = v.subtract(new BigDecimal(vBaseK));//当前日的v减去前一天的对应的k的v值
                    elm.put(k, df.format(newV.multiply(new BigDecimal("10000"))));//*10000转为BP显示
                }
            }
            return elm;
        }).collect(Collectors.toList());
        return new PageInfo<>(collect);
    }

    @Override
    public Map<String, Object> dataProcess(Map<String, Object> params) {
        Map<String, Object> map = new HashMap();
        List<Object> table1 = processTable(params.get("table1"));
        map.put("size1", table1.get(table1.size() - 1));
        map.put("len1", table1.get(table1.size() - 2));
        List<Object> table2 = processTable(params.get("table2"));
        map.put("size2", table2.get(table2.size() - 1));
        map.put("len2", table2.get(table2.size() - 2));

        //清除size
        table1.remove(table1.size() - 1);
        table1.remove(table1.size() - 1);
        table2.remove(table2.size() - 1);
        table2.remove(table2.size() - 1);
        map.put("table1", table1);
        map.put("table2", table2);


        return map;
    }

    List<Object> processTable(Object s) {
        if (s.toString().isEmpty()) {
            return null;
        }
        //String str = "[" + s.toString() + "]";
        String str =s.toString();
        str = str.replaceAll("IRC_CODE", "曲线名称").replaceAll("\n", "");
        List<Object> list = new ArrayList<>();//放数据
        List<LinkedHashMap> objects = JSON.parseArray(str, LinkedHashMap.class);
        Set<String> strings1 = objects.get(0).keySet();
        List<String> title = new ArrayList<>();
        //处理标题
        HashMap<String, Object> param = new HashMap<>();
        param.put("DICT_TYPE", "irCurveArea");
        List<Map> maps = dictMapper.queryIrDictByKey(param);
        Map<String, String> titles = new HashMap();
        for (Map m : maps) {
            titles.put(m.get("DICT_KEY").toString(), m.get("DICT_VALUE").toString());
        }
        for (String s1 : strings1) {
            title.add(titles.get(s1) == null ? s1 : titles.get(s1));
        }
        list.add(title);
        for (LinkedHashMap<String, String> o : objects) {
            List<String> col = new ArrayList<>();
            for (String key : o.keySet()) {
                String o1 = o.get(key);
                col.add(o1);
            }
            list.add(col);
//            col = new ArrayList<>();
        }
        int cols = objects.get(0).keySet().size() - 1;
        Integer i = 9000 / objects.get(0).keySet().size();
        list.add(i.toString());
        list.add(cols);
        return list;
    }

}
